<!--
<template>
  <div class="comment-container">
    &lt;!&ndash; 头部：标题 + 写评价按钮 &ndash;&gt;
    <header class="header">
      <h1 class="title">用户评价</h1>
      <el-button type="primary" @click="openDialog">填写评价</el-button>
    </header>

    &lt;!&ndash; 评论列表 &ndash;&gt;
    <section class="list">
      <el-card
          v-for="item in comments"
          :key="item.id"
          class="comment-card"
          shadow="hover"
      >
        <div class="card-top">
          <img class="avatar" :src="item.userAvatar || defaultAvatar" alt="avatar" />
          <div class="meta">
            <div class="user-row">
              <span class="user-name">{{ item.userName || '匿名用户' }}</span>
              <span class="dot">·</span>
              <span class="time">{{ formatDate(item.createTime) }}</span>
            </div>
            <div class="course-row">
              <strong class="course-name">{{ item.courseName || '-' }}</strong>
              <span class="sep">|</span>
              <span class="coach">教练：{{ item.coachName || '-' }}</span>
            </div>
          </div>

          <div class="rate">
            <el-rate
                :model-value="item.rating"
                :max="5"
                readonly
                allow-half
                class="yellow-rate"
            />
          </div>
        </div>

        <div class="card-body">
          <p class="content">{{ item.content }}</p>
        </div>
      </el-card>

      <div v-if="comments.length === 0" class="no-data">
        暂无评价，快来成为第一个评价的人吧！
      </div>
    </section>

    &lt;!&ndash; 写评价弹窗 &ndash;&gt;
    <el-dialog v-model="dialogVisible" title="填写评价" width="560px" :destroy-on-close="true">
      <el-form :model="form" label-width="100px">
        <el-form-item label="请选择课程" required>
          <el-select v-model="form.courseId" placeholder="选择课程" @change="onCourseChange">
            <el-option
                v-for="c in userCourses"
                :key="c.id"
                :label="`${c.name}（${c.coachName || '无教练'}）${c.alreadyEvaluated ? ' - 已评价' : ''}`"
                :value="c.id"
                :disabled="c.alreadyEvaluated"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="评分" required>
          <el-rate v-model="form.rating" :max="5" allow-half />
        </el-form-item>

        <el-form-item label="评价内容" required>
          <el-input
              type="textarea"
              v-model="form.content"
              placeholder="写下你的体验，帮助其他学员"
              :rows="5"
              maxlength="500"
              show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import commentApi from '@/api/commentApi.js'
import reserveApi from '@/api/reserve.js'
import courseApi from '@/api/course.js'
import { useUserInfoStore } from '@/store/userInfo.js'

const userInfoStore = useUserInfoStore()

const dialogVisible = ref(false)
const comments = ref([])
const defaultAvatar = 'https://img.icons8.com/ios-filled/50/000000/user.png'

const form = ref({
  courseId: null,
  courseName: '',
  coachName: '',
  rating: 0,
  content: ''
})

// 下拉列表显示用户预约过的课程，并标记已评价的课程
const userCourses = ref([])

const openDialog = async () => {
  dialogVisible.value = true
  await loadUserCourses()
}

const loadUserCourses = async () => {
  try {
    // 查询当前用户预约的课程
    const reserveRes = await reserveApi.list({
      userId: userInfoStore.userId,
      page: 1,
      limit: 100
    })

    if (!reserveRes || reserveRes.code !== 0) {
      userCourses.value = []
      ElMessage.warning(reserveRes?.msg || '获取预约课程失败')
      return
    }

    const courseIds = reserveRes.data.records.map(r => r.courseId)
    if (courseIds.length === 0) {
      userCourses.value = []
      ElMessage.warning('您暂无预约课程，无法评价')
      return
    }

    // 查询用户已有的评价
    const commentRes = await commentApi.selectAll({ userId: userInfoStore.userId })
    let evaluatedCourseIds = []
    if (commentRes && commentRes.code === 0) {
      evaluatedCourseIds = (commentRes.data || []).map(c => c.courseId)
    }

    // 获取课程信息，包括 coachName
    const courseRes = await courseApi.selectAll()
    if (courseRes && courseRes.code === 0) {
      userCourses.value = courseRes.data
          .filter(c => courseIds.includes(c.id))
          .map(c => ({
            ...c,
            alreadyEvaluated: evaluatedCourseIds.includes(c.id)
          }))
    } else {
      userCourses.value = []
      ElMessage.warning(courseRes.msg || '获取课程信息失败')
    }
  } catch (err) {
    console.error('loadUserCourses error', err)
    userCourses.value = []
    ElMessage.error('获取预约课程失败，请稍后重试')
  }
}

const loadComments = async () => {
  try {
    const res = await commentApi.selectAll()
    if (res && res.code === 0) {
      comments.value = (res.data || []).map(item => ({
        ...item,
        rating: Number(item.rating) || 0
      }))
    } else {
      comments.value = []
      ElMessage.warning(res?.msg || '获取评论失败')
    }
  } catch (err) {
    console.error('loadComments error', err)
    comments.value = []
    ElMessage.error('获取评论失败，请稍后重试')
  }
}

const onCourseChange = (courseId) => {
  const c = userCourses.value.find(x => x.id === courseId)
  if (c) {
    form.value.courseName = c.name || ''
    form.value.coachName = c.coachName || ''
  } else {
    form.value.courseName = ''
    form.value.coachName = ''
  }
}

const submit = async () => {
  const user = userInfoStore.user || {}
  if (!user || !user.id) {
    ElMessage.warning('请先登录后再发表评论')
    return
  }
  if (!form.value.courseId) {
    ElMessage.warning('请选择课程')
    return
  }
  if (!(form.value.rating > 0)) {
    ElMessage.warning('请给出评分')
    return
  }
  if (!form.value.content || form.value.content.trim().length === 0) {
    ElMessage.warning('请输入评价内容')
    return
  }

  const payload = {
    courseId: form.value.courseId,
    courseName: form.value.courseName,
    coachName: form.value.coachName,
    rating: form.value.rating,
    content: form.value.content,
    userId: user.id,
    userName: user.name || '匿名',
    userAvatar: user.avatar || ''
  }

  try {
    const res = await commentApi.add(payload)
    if (res && res.code === 0) {
      ElMessage.success('提交成功')
      dialogVisible.value = false
      form.value = { courseId: null, courseName: '', coachName: '', rating: 0, content: '' }
      await loadComments()
    } else {
      ElMessage.error(res?.msg || '提交失败')
    }
  } catch (err) {
    console.error('submit comment error', err)
    ElMessage.error('提交失败，请稍后重试')
  }
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  if (isNaN(d.getTime())) return dateStr
  const Y = d.getFullYear()
  const M = String(d.getMonth() + 1).padStart(2, '0')
  const D = String(d.getDate()).padStart(2, '0')
  const h = String(d.getHours()).padStart(2, '0')
  const m = String(d.getMinutes()).padStart(2, '0')
  return `${Y}-${M}-${D} ${h}:${m}`
}

onMounted(() => {
  loadComments()
})
</script>

<style scoped>
.comment-container {
  min-height: 100vh;
  padding: 24px;
  background: #f6f7f9;
  box-sizing: border-box;
  font-family: "Helvetica Neue", Arial, sans-serif;
}

/* header */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  margin: 0;
  font-size: 22px;
  color: #333;
}

/* 列表 */
.list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 卡片 */
.comment-card {
  padding: 16px;
  border-radius: 10px;
  background: #fff;
  box-shadow: 0 6px 18px rgba(34, 34, 34, 0.06);
}

/* 顶部meta */
.card-top {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  flex-shrink: 0;
}

.meta {
  flex: 1;
  min-width: 0;
}

.user-row {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #333;
  font-size: 15px;
}

.user-name {
  font-weight: 600;
}

.dot {
  color: #bbb;
}

.time {
  color: #999;
  font-size: 12px;
}

.course-row {
  margin-top: 6px;
  color: #666;
  font-size: 13px;
}

.course-name {
  color: #333;
  margin-right: 6px;
}

.sep {
  margin: 0 6px;
  color: #ddd;
}

.coach {
  color: #666;
}

/* 评分 */
.rate {
  margin-left: 8px;
}

/* 列表中的星星样式 */
.yellow-rate :deep(.el-rate__item i) {
  color: #f7ba2a !important;
  font-size: 20px;
}

.yellow-rate :deep(.el-rate__item) {
  margin-right: 4px;
}

.yellow-rate :deep(.el-rate__item:last-child) {
  margin-right: 0;
}

/* 正文 */
.card-body {
  margin-top: 12px;
}

.content {
  color: #333;
  line-height: 1.6;
  white-space: pre-wrap;
}

/* 无数据提示 */
.no-data {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

/* 响应式 */
@media (max-width: 768px) {
  .comment-container {
    padding: 12px;
  }

  .avatar {
    width: 40px;
    height: 40px;
  }

  .title {
    font-size: 18px;
  }

  .comment-card {
    padding: 12px;
  }
}
</style>-->

<template>
  <div class="comment-container">
    <!-- 头部：标题 + 写评价按钮 -->
    <header class="header">
      <h1 class="title">用户评价</h1>
      <el-button type="primary" @click="openDialog">填写评价</el-button>
    </header>

    <!-- 评论列表 -->
    <section class="list">
      <el-card
          v-for="item in comments"
          :key="item.id"
          class="comment-card"
          shadow="hover"
      >
        <div class="card-top">
          <img class="avatar" :src="item.userAvatar || defaultAvatar" alt="avatar" />
          <div class="meta">
            <div class="user-row">
              <span class="user-name">{{ item.userName || '匿名用户' }}</span>
              <span class="dot">·</span>
              <span class="time">{{ formatDate(item.createTime) }}</span>
            </div>
            <div class="course-row">
              <strong class="course-name">{{ item.courseName || '-' }}</strong>
              <span class="sep">|</span>
              <span class="coach">教练：{{ item.coachName || '-' }}</span>
            </div>
          </div>

          <div class="rate">
            <el-rate
                :model-value="item.rating"
                :max="5"
                readonly
                allow-half
                class="yellow-rate"
            />
          </div>
        </div>

        <div class="card-body">
          <p class="content">{{ item.content }}</p>
        </div>
      </el-card>

      <div v-if="comments.length === 0" class="no-data">
        暂无评价，快来成为第一个评价的人吧！
      </div>
    </section>

    <!-- 写评价弹窗 -->
    <el-dialog v-model="dialogVisible" title="填写评价" width="560px" :destroy-on-close="true">
      <el-form :model="form" label-width="100px">
        <el-form-item label="请选择课程" required>
          <el-select v-model="form.courseId" placeholder="选择课程" @change="onCourseChange">
            <el-option
                v-for="c in userCourses"
                :key="c.id"
                :label="`${c.name}（${c.coachName || '无教练'}）${c.alreadyEvaluated ? ' - 已评价' : ''}`"
                :value="c.id"
                :disabled="c.alreadyEvaluated"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="评分" required>
          <el-rate v-model="form.rating" :max="5" allow-half />
        </el-form-item>

        <el-form-item label="评价内容" required>
          <el-input
              type="textarea"
              v-model="form.content"
              placeholder="写下你的体验，帮助其他学员"
              :rows="5"
              maxlength="500"
              show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import commentApi from '@/api/commentApi.js'
import reserveApi from '@/api/reserve.js'
import courseApi from '@/api/course.js'
import { useUserInfoStore } from '@/store/userInfo.js'

const userInfoStore = useUserInfoStore()
const dialogVisible = ref(false)
const comments = ref([])
const defaultAvatar = 'https://img.icons8.com/ios-filled/50/000000/user.png'

const form = ref({
  courseId: null,
  courseName: '',
  coachName: '',
  rating: 0,
  content: ''
})

// 当前用户的预约课程，并标记已评价
const userCourses = ref([])

const openDialog = async () => {
  dialogVisible.value = true
  await loadUserCourses()
}

const loadUserCourses = async () => {
  try {
    const userId = userInfoStore.userId
    if (!userId) {
      userCourses.value = []
      ElMessage.warning('请先登录')
      return
    }

    // 获取当前用户预约的课程
    const reserveRes = await reserveApi.list({ userId, page: 1, limit: 100 })
    if (!reserveRes || reserveRes.code !== 0) {
      userCourses.value = []
      ElMessage.warning(reserveRes?.msg || '获取预约课程失败')
      return
    }

    const courseIds = reserveRes.data.records.map(r => r.courseId)
    if (courseIds.length === 0) {
      userCourses.value = []
      ElMessage.warning('您暂无预约课程，无法评价')
      return
    }

    // 获取当前用户已评价的课程
    const commentRes = await commentApi.selectAll({ userId })
    const evaluatedCourseIds = (commentRes && commentRes.code === 0)
        ? (commentRes.data || []).map(c => c.courseId)
        : []

    // 获取课程信息
    const courseRes = await courseApi.selectAll()
    if (courseRes && courseRes.code === 0) {
      userCourses.value = courseRes.data
          .filter(c => courseIds.includes(c.id))
          .map(c => ({
            ...c,
            alreadyEvaluated: evaluatedCourseIds.includes(c.id) // 只针对当前用户
          }))
    } else {
      userCourses.value = []
      ElMessage.warning(courseRes.msg || '获取课程信息失败')
    }
  } catch (err) {
    console.error('loadUserCourses error', err)
    userCourses.value = []
    ElMessage.error('获取预约课程失败，请稍后重试')
  }
}

const loadComments = async () => {
  try {
    const res = await commentApi.selectAll()
    if (res && res.code === 0) {
      comments.value = (res.data || []).map(item => ({
        ...item,
        rating: Number(item.rating) || 0
      }))
    } else {
      comments.value = []
      ElMessage.warning(res?.msg || '获取评论失败')
    }
  } catch (err) {
    console.error('loadComments error', err)
    comments.value = []
    ElMessage.error('获取评论失败，请稍后重试')
  }
}

const onCourseChange = (courseId) => {
  const c = userCourses.value.find(x => x.id === courseId)
  if (c) {
    form.value.courseName = c.name || ''
    form.value.coachName = c.coachName || ''
  } else {
    form.value.courseName = ''
    form.value.coachName = ''
  }
}

const submit = async () => {
  const user = userInfoStore.user || {}
  if (!user || !user.id) {
    ElMessage.warning('请先登录后再发表评论')
    return
  }
  if (!form.value.courseId) {
    ElMessage.warning('请选择课程')
    return
  }
  if (!(form.value.rating > 0)) {
    ElMessage.warning('请给出评分')
    return
  }
  if (!form.value.content || form.value.content.trim().length === 0) {
    ElMessage.warning('请输入评价内容')
    return
  }

  const payload = {
    courseId: form.value.courseId,
    courseName: form.value.courseName,
    coachName: form.value.coachName,
    rating: form.value.rating,
    content: form.value.content,
    userId: user.id,
    userName: user.name || '匿名',
    userAvatar: user.avatar || ''
  }

  try {
    const res = await commentApi.add(payload)
    if (res && res.code === 0) {
      ElMessage.success('提交成功')
      dialogVisible.value = false
      form.value = { courseId: null, courseName: '', coachName: '', rating: 0, content: '' }
      await loadComments()
    } else {
      ElMessage.error(res?.msg || '提交失败')
    }
  } catch (err) {
    console.error('submit comment error', err)
    ElMessage.error('提交失败，请稍后重试')
  }
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  if (isNaN(d.getTime())) return dateStr
  const Y = d.getFullYear()
  const M = String(d.getMonth() + 1).padStart(2, '0')
  const D = String(d.getDate()).padStart(2, '0')
  const h = String(d.getHours()).padStart(2, '0')
  const m = String(d.getMinutes()).padStart(2, '0')
  return `${Y}-${M}-${D} ${h}:${m}`
}

onMounted(() => {
  loadComments()
})
</script>

<style scoped>
.comment-container {
  min-height: 100vh;
  padding: 24px;
  background: #f6f7f9;
  box-sizing: border-box;
  font-family: "Helvetica Neue", Arial, sans-serif;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  margin: 0;
  font-size: 22px;
  color: #333;
}

.list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.comment-card {
  padding: 16px;
  border-radius: 10px;
  background: #fff;
  box-shadow: 0 6px 18px rgba(34,34,34,0.06);
}

.card-top {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  flex-shrink: 0;
}

.meta {
  flex: 1;
  min-width: 0;
}

.user-row {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #333;
  font-size: 15px;
}

.user-name {
  font-weight: 600;
}

.dot { color: #bbb; }
.time { color: #999; font-size: 12px; }

.course-row { margin-top:6px; color:#666; font-size:13px; }
.course-name { color:#333; margin-right:6px; }
.sep { margin:0 6px; color:#ddd; }
.coach { color:#666; }

.rate { margin-left: 8px; }

.yellow-rate :deep(.el-rate__item i) { color:#f7ba2a !important; font-size:20px; }
.yellow-rate :deep(.el-rate__item) { margin-right:4px; }
.yellow-rate :deep(.el-rate__item:last-child) { margin-right:0; }

.card-body { margin-top:12px; }
.content { color:#333; line-height:1.6; white-space:pre-wrap; }
.no-data { text-align:center; color:#999; padding:40px 0; }

@media (max-width:768px){
  .comment-container { padding:12px; }
  .avatar { width:40px; height:40px; }
  .title { font-size:18px; }
  .comment-card { padding:12px; }
}
</style>

